#!/bin/bash

set -x

. .env

sshUser=${1:-root}
sshPass=${2:-zxcasd123}

harborNodes=(${3:-10.184.147.231})
harbornodesToJson=$(printf '%s\n' "${harborNodes[@]}"|sed 's/.*/"&"/;$!s/$/,/')

harborVersion=v1.2.2


### 工作目录 ###
mkdir -p harbor; cd harbor

### 远程函数 ###
sshCmd(){
  sudo sshpass -p $2 ssh -o StrictHostKeyChecking=no "${1}@${3}" "$4"
}

sshCopy(){
  sudo sshpass -p $2 scp -r -o StrictHostKeyChecking=no $4 "${1}@${3}:$5"
}

### CA ###
# 创建ca-config.json文件
cat > ca-config.json <<EOF
{
    "signing": {
        "default": {
            "expiry": "87600h"
        },
        "profiles": {
            "yzh": {
                "expiry": "87600h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth",
                    "client auth"
                ]
            }
        }
    }
}
EOF

# 创建ca-csr.json文件
cat > ca-csr.json <<EOF
{
    "CN": "yzh",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "ShangHai",
            "L": "ShangHai",
            "O": "yzh",
            "OU": "DevOps"
        }
    ]
}
EOF

# 生成ca证书和私钥
cfssl gencert -initca ca-csr.json | cfssljson -bare ca

### harbor ###
# 创建harbor-csr.json
cat > harbor-csr.json <<EOF
{
    "CN": "harbor",
    "hosts": [
       "127.0.0.1",
       $harbornodesToJson
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "ShangHai",
            "L": "ShangHai",
            "O": "yzh",
            "OU": "DevOps"
        }
    ]
}
EOF

# 生成harbor证书和私钥
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=yzh harbor-csr.json | cfssljson -bare harbor


# 查看证书信息
# 1. openssl x509  -noout -text -in  harbor.pem
# 2. cfssl-certinfo -cert harbor.pem

# 下载harbor
[ -f harbor-online-installer-${harborVersion}.tgz ] || wget https://github.com/vmware/harbor/releases/download/${harborVersion}/harbor-online-installer-${harborVersion}.tgz


# 将证书以及harbor.service文件分发到个节点
sshCmd $sshUser $sshPass $harborNodes "rm -rf /data/* /opt/harbor"
sshCopy $sshUser $sshPass $harborNodes "harbor-online-installer-${harborVersion}.tgz"  /opt/
sshCmd $sshUser $sshPass $harborNodes "tar xf /opt/harbor-online-installer-${harborVersion}.tgz -C /opt/; sed -i '/ui_url_protocol/s/http/&s/g;s/reg.mydomain.com/${harborNodes}/;s/server.crt/harbor.pem/g;s/server.key/harbor-key.pem/g' /opt/harbor/harbor.cfg; mkdir -p /data/cert/"
sshCopy $sshUser $sshPass $harborNodes "harbor*.pem" /data/cert/
sshCopy $sshUser $sshPass $harborNodes "ca.pem" /etc/docker/certs.d/$harborNodes/ca.crt
sshCmd $sshUser $sshPass $harborNodes "/opt/harbor/install.sh --with-notary"

